/*
 * dynmisc.c
 * KJ's simplified stream archiver (kjssar)
 * 
 * (C)Copyright 2013-2015 by Klaus-J. Wolf, kj (at) seismic (dot) de
 * This file is licensed under the General Public License Version 2.
 * http://www.gnu.org/licenses/gpl-2.0.html
 * 
 * This is a proof-of-concept implementation.
 * 
 */


#include <stdlib.h>
#include <string.h>

#include "dynmisc.h"


uchar *concatfn_f(const uchar *a, const uchar *b)
{
    int na = strlen(a);
    int n = na + strlen(b) + 2;
    char *r = malloc(n);
    
    MEMASSERT(r,NULL)
    strcpy(r, a);
    if(na>0 && r[na-1]!='/')
        strcat(r, "/");
    strcat(r, b);
    return r;
}


int escctl(const uchar *s, uchar *buf, int m)
{
    int p1=0, p2=0, n, guessedsz;
    
    n=strlen(s);
    guessedsz=n+1;
    
    while(p1<n && s[p1])
    {
        if(s[p1]<0x20 || s[p1]=='\\' || (s[p1] & 0x80))
        {
            guessedsz+=2;
            if(guessedsz>=m)
                return 1;
            buf[p2++] = '\n';
            tohex(buf+p2, s[p1]);
            p2+=2; p1++;
        }
        else
            buf[p2++] = s[p1++];
    }
    buf[p2]=0;
    return 0;
}


void tohex(uchar *p, uint16 x)
{
    uint16 a = ((x>>4)&0xf), b = (x&0xf);
    
    a+='0';
    b+='0';
    if(a>'9')
        a+='a'-'0'-10;
    if(b>'9')
        b+='a'-'0'-10;
    p[0]=a;
    p[1]=b;
}


int concatentry(uchar *buf, int bufsz, uchar *np, uchar *vp, int vsz)
{
    int i;
    int pos = strlen(buf);
    int esz = strlen(np) + 3 + vsz*2;
    if(esz+pos>=bufsz)
        return 1;    /* error: too few memory */
    strcpy(buf+pos, np);
    buf[pos+1]='=';
    for(i=0; i<vsz; i++)
        tohex(buf+pos+1+i*2, vp[i]);
    buf[pos+1+vsz*2]=';';
    buf[pos+1+vsz*2+1]=0;
    return 0; /* OK */
}
